//
//  MeNewAddressViewController.m
//  ChinaA
//
//  Created by Mxionlly on 2018/10/30.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "MeNewAddressViewController.h"
#import "MeAuthenticationTableViewCell.h"
#import "taskUserManagerService.h"
#import "UINavigationItem+Item.h"

@interface MeNewAddressViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic,strong)UITableView    *tableView;
@property (nonatomic,strong)NSArray        *cellArray;

@property (nonatomic,strong)NSString *uName;
@property (nonatomic,strong)NSString *uPhone;
@property (nonatomic,strong)NSString *Des;
@property (nonatomic,strong)NSString *doorNumber;
@end

@implementation MeNewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.isModify ? @"修改地址":@"新增地址";
    self.cellArray = @[@[@"联系人",@"手机号码",@"地址",@"门牌号"],@[@"请输入收件人姓名",@"请输入收件人号码",@"请输入详细地址",@"例：5号楼803室"]];
    [self.view addSubview:self.tableView];
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSliderAction)]];
    
    if (self.isModify == 1) {
        [self.navigationItem setItem:@"删除地址" image:nil highlightImage:nil target:self selector:@selector(rightButtonAction) color:[UIColor whiteColor] left:NO enabled:YES];
    }
}

-(void)setModel:(dataAddressModel *)model
{
    _model = model;
    self.uName = model.Name;
    self.uPhone = model.Phone;
    self.Des = model.Des;
    self.doorNumber = model.DoorNumber;
    [self.tableView reloadData];
}

-(void)rightButtonAction
{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:self.model.ID value:@"receId"];
    [taskUserManagerService getDeleteReceivingAddress:dict success:^(BaseModel *response, BOOL success) {
        if (success) {
            [DKProgressHUD showSuccessWithStatus:@"删除成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [DKProgressHUD showErrorWithStatus:response.message];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setBlackStatus:YES];
}

#pragma mark - init
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, distanceHeight, KScreenWidth, KScreenHeight-distanceHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
        _tableView.scrollEnabled = YES;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

#pragma mark - UITableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellArray[0] count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 100)];
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(80, 50, KScreenWidth - 160, 40);
    nextButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [nextButton setBackgroundImage:[UIImage imageNamed:@"icon_button"] forState:UIControlStateNormal];
    [nextButton setTitle:@"确定" forState:UIControlStateNormal];
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:nextButton];
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MeAuthenticationTableViewCell *cell = [MeAuthenticationTableViewCell cellWithTableView:tableView];
    cell.textField.tag = indexPath.row;
    cell.textField.delegate = self;
    cell.textField.userInteractionEnabled = YES;
    cell.textField.keyboardType = UIKeyboardTypeDefault;
    cell.lbtitle.text =self.cellArray[0][indexPath.row];
    cell.textField.placeholder = self.cellArray[1][indexPath.row];
    switch (indexPath.row) {
        case 0:
        {
            cell.textField.text = self.uName;
        }
            break;
        case 1:
        {
            cell.textField.text =self.uPhone;
            cell.textField.keyboardType = UIKeyboardTypePhonePad;
        }
            break;
        case 2:
        {
            cell.textField.text =self.Des;
        }
            break;
        case 3:
        {
            cell.textField.text =self.doorNumber;
        }
            break;
        default:
            break;
    }
    return cell;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
        {
            self.uName = textField.text;
        }
            break;
        case 1:
        {
            self.uPhone =textField.text;
        }
            break;
        case 2:
        {
            self.Des = textField.text;
        }
            break;
        case 3:
        {
            self.doorNumber = textField.text;
        }
            break;
        default:
            break;
    }
}

-(void)doneAction{
    [self.view endEditing:YES];
    if (![Check checkLenght:self.uName]) {
        [DKProgressHUD showErrorWithStatus:@"请输入收件人姓名"];
        return;
    }
    if (![Check checkLenght:self.uPhone]) {
        [DKProgressHUD showErrorWithStatus:@"请输入收件人号码"];
        return;
    }
    if (![Check checkLenght:self.Des]) {
        [DKProgressHUD showErrorWithStatus:@"请输入详细地址"];
        return;
    }

    if (![Check checkLenght:self.doorNumber]) {
        [DKProgressHUD showErrorWithStatus:@"请输入门牌号码"];
        return;
    }

    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:self.uPhone value:@"uPhone"];
    [dict setField:self.uName value:@"uName"];
    [dict setField:self.Des value:@"Des"];
    [dict setField:self.doorNumber value:@"doorNumber"];
    [dict setField:self.model.ID value:@"recId"];
    if (self.isModify == 0) {
        [taskUserManagerService getAddReceivingAddress:dict success:^(BaseModel *response, BOOL success) {
            if (success) {
                [DKProgressHUD showSuccessWithStatus:@"新增成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [DKProgressHUD showErrorWithStatus:response.message];
            }
        } failture:^(NSError *error, NSString *strDescription) {
            [DKProgressHUD dismiss];
            [DKProgressHUD showErrorWithStatus:strDescription];
        }];
    }else{
        [taskUserManagerService getModifyReceivingAddressn:dict success:^(BaseModel *response, BOOL success) {
            if (success) {
                [DKProgressHUD showSuccessWithStatus:@"修改成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [DKProgressHUD showErrorWithStatus:response.message];
            }
        } failture:^(NSError *error, NSString *strDescription) {
            [DKProgressHUD dismiss];
            [DKProgressHUD showErrorWithStatus:strDescription];
        }];
    }
}

-(void)tapSliderAction
{
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
